import 'dart:io';
import 'package:basic_library/basic_library.dart';
import 'package:flutter/material.dart';

///
/// 弹出文件下载组件
///
class QDownloadFileAlert extends Dialog {
  final BuildContext buildContext;
  final String fileName;
  final String msgContent;
  final Function(String path)? onTap;

  const QDownloadFileAlert({
    Key? key,
    required this.buildContext,
    required this.fileName,
    this.msgContent = '您下载查看合同吗？',
    this.onTap,
  }) : super(key: key);

  /// 取消对话框
  static hide(BuildContext context) {
    Navigator.of(context).pop();
  }

  /// 显示对话框
  void show() {
    QConfirmAlert(
      buildContext: buildContext,
      buttonItems: const ['取消', '下载'],
      title: '',
      content: msgContent,
      onTap: (index) {
        // Navigator.pop(buildContext);
        if (index == 1) {
          _createPath(buildContext, fileName, onTap: onTap);
        }
      },
    ).show();
  }

  static _createPath(context, name, {Function(String path)? onTap}) async {
    /// 申请写文件权限
    bool isPermission = await requestPermissions([Permission.storage]);
    String _localPath = "";
    if (isPermission) {
      Directory _path = await getApplicationDocumentsDirectory();
      _localPath = _path.path + Platform.pathSeparator + 'Download';
      final savedDir = Directory(_localPath);
      bool hasExisted = await savedDir.exists();
      if (!hasExisted) {
        savedDir.create();
      }

      if (_localPath.isNotEmpty) {
        onTap!.call(_localPath + "/" + name);
      }
    } else {
      // 提示用户请同意权限申请
      isPermission = await requestPermissions([Permission.storage]);
    }
    debugPrint("路径" + _localPath);
  }
}
